<template>
  <div class="self_adaption">
    <div class="order_content">
      <ul class="nav_ul">
        <li
          v-for="(item, index) in list"
          :key="index"
          :class="item.class"
          @click="navChange(item)"
          style="cursor: pointer;"
        >
          {{ item.text }}
        </li>
      </ul>
      <!-- 时限设置 -->
      <div v-show="route == 1">
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#F5F7FA', 'text-align': 'center' }"
        >
          <el-table-column label="售后方式" min-width="220">
            <template #default="item">
              {{ item.row.description }}
            </template>
          </el-table-column>
          <el-table-column label="原因类型" min-width="600">
            <template #default="item">
              <div style="display: flex">
                &nbsp;&nbsp;&nbsp;
                <el-input
                  v-model="item.row.value"
                  style="max-width: 80px"
                  :disabled="!item.row.afterSaleShow"
                />&nbsp;&nbsp;&nbsp;
                <el-select
                  v-model="item.row.timeUnit"
                  class="m-2"
                  placeholder="请选择商品状态"
                  :disabled="!item.row.afterSaleShow"
                  style="max-width: 120px"
                >
                  <el-option
                    v-for="item in status_options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                /></el-select>

                &nbsp;
                {{ item.row.result }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="enable" label="是否启用" width="80">
            <template #default="item">
              <el-switch
                v-model="item.row.enable"
                :disabled="!item.row.afterSaleShow"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="200"
            class="operation"
            align="center"
          >
            <template #default="item">
              <div v-show="!item.row.afterSaleShow">
                <el-button
                  class="none"
                  @click="setupEdit(item.row, item.$index)"
                  >修改</el-button
                >
              </div>
              <div v-show="item.row.afterSaleShow">
                <el-button class="none" @click="Edit1(item.row)"
                  >确认</el-button
                >
                <el-button class="none" @click="cancle(item.row, item.$index)"
                  >取消</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="备注" width="300" align="center">
            <template #default="item">
              <el-input
                v-model="item.row.note"
                style="width: 200px"
                :disabled="!item.row.afterSaleShow"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 售后原因 -->
      <div v-show="route == 0">
        <el-table
          border
          :data="tableDataCase"
          style="width: 100%"
          :header-cell-style="{ background: '#F5F7FA', 'text-align': 'center' }"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column prop="type" label="售后方式" width="160">
            <template #default="scope">
              <span v-if="scope.row.status == 1">退货退款</span>
              <span v-else-if="scope.row.status == 2">退款</span>
              <span v-else>换货</span>
            </template>
          </el-table-column>
          <el-table-column prop="reason" label="原因类型" min-width="200" />
          <el-table-column prop="enable" label="是否启用" width="80">
            <template #default="item">
              <el-switch
                v-model="item.row.enable"
                :disabled="!item.row.afterSaleShow"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="添加时间" width="200" />
          <el-table-column
            label="操作"
            width="200"
            class="operation"
            align="center"
          >
            <template #default="item">
              <div v-show="!item.row.afterSaleShow">
                <el-button
                  class="none"
                  @click="setupEdit(item.row, item.$index)"
                  >修改</el-button
                >
              </div>
              <div v-show="item.row.afterSaleShow">
                <el-button class="none" @click="Sure(item.row)">确认</el-button>
                <el-button class="none" @click="cancle(item.row, item.$index)"
                  >取消</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" min-width="300">
            <template #default="item">
              <el-input
                v-model="item.row.note"
                :disabled="!item.row.afterSaleShow"
                autosize
                type="textarea"
                input-style="background:transparent;border:0;"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 比例设置 -->
      <div v-show="route == 2">
        <el-button class="solid add_btn" @click="AddProportion">添加</el-button>
        <el-table
          border
          :data="tableDataRatio"
          style="width: 100%"
          :header-cell-style="{ background: '#F5F7FA', 'text-align': 'center' }"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column prop="drawType" label="设置说明" />
          <el-table-column prop="proportion" label="设置比例">
            <template #default="item"> {{ item.row.proportion }}% </template>
          </el-table-column>
          <el-table-column label="操作" class="operation" align="center">
            <template #default="item">
              <div v-show="!item.row.afterSaleShow">
                <el-button
                  class="none"
                  @click="proportionEdit(item.row, item.$index)"
                  >修改</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注">
            <template #default="item">
              <el-input
                v-model="item.row.note"
                :disabled="!item.row.afterSaleShow"
                autosize
                type="textarea"
                input-style="background:transparent;border:0;"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加模板 -->
      <div class="messages" v-if="messagesShow">
        <div class="title1">
          <div class="title_mes">
            <el-icon size="20" color="#fff"><Edit /></el-icon>&nbsp;添加模板
          </div>
          <span class="close" @click="maskBtn1">✖</span>
        </div>
        <div class="content1" style="margin-top: 40px">
          <el-form
            ref="ruleFormRef"
            :model="GoodsformDate"
            label-width="90px"
            label-position="right"
            :rules="rules"
          >
            <el-form-item label="设置说明:" prop="drawType">
              <el-input
                v-model="GoodsformDate.drawType"
                class="form_input"
                type="text"
                placeholder="请输入标题"
                :disabled="type=='Edit'"
              ></el-input>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="设置比例:" prop="proportion">
              <el-input
                v-model="GoodsformDate.proportion"
                class="form_input"
                type="text"
                placeholder="请输入内容"
              ></el-input>
              <span id="input_hint"></span>
            </el-form-item>
            <el-form-item label="备注:" prop="note">
              <el-input
                v-model="GoodsformDate.note"
                cols="30"
                rows="4"
                class="form_input"
                maxlength="300"
                type="textarea"
                show-word-limit
                placeholder="请输入内容"
              ></el-input>
              <span id="input_hint"></span>
            </el-form-item>
          </el-form>
          <div class="btn_center">
            <el-button class="hollow" @click="maskBtn1">取消</el-button>
            <el-button class="solid" @click="plateformSure">确定</el-button>
          </div>
        </div>
      </div>
      <!-- 遮罩层 -->
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {
  RequestAllSetting,
  RequestSettingEdit,
  RequestAllCause,
  RequestAllCauseEdit,
  RequestScaleSetting,
  RequestAddScaleSetting,
} from "@/api/path/index.js";
import { ElMessage } from "element-plus";
import { Warning, Edit, User } from "@element-plus/icons-vue";
const verify = ref(false);
onMounted(() => {
  requestsetting();
});

// 表单规则
const rules = reactive({
  proportion: [{ required: true, message: "请输入比例", trigger: "blur" }],
  // unit: [{ required: true, message: '请选择商品单位', trigger: 'change' }],
  drawType: [{ required: true, message: "请输入设置说明", trigger: "blur" }],
  note: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const messagesShow = ref(false); //控制模板添加框的显示
const mask = ref(false); //控制遮罩层显示
const route = ref(0);
const GoodsformDate = ref({
  drawType: "",
  proportion: "",
  note: "",
});
const list = ref([
  {
    route: 0,
    class: ["current", "nav_li", "first_li"],
    text: "售后原因",
  },
  {
    route: 1,
    class: ["nav_li"],
    text: "时限设置",
  },
  {
    route: 2,
    class: ["nav_li"],
    text: "比例设置",
  },
]);
/**
 * 状态选择器
 */
const status_options = [
  {
    value: "m",
    label: "分钟",
  },
  {
    value: "h",
    label: "小时",
  },
  {
    value: "d",
    label: "天",
  },
];

const tableData = ref([]);
const tableDataCase = ref([]);
const tableDataRatio = ref([]);
/**
 * 获取所有平台设置
 */
const requestsetting = async () => {
  const c = await RequestScaleSetting();
  if (c.msg == "操作成功！") {
    console.log("比例设置");
    tableDataRatio.value = c.resultObj;
  }
  const a = await RequestAllSetting();
  if (a.msg == "操作成功！") {
    tableData.value = a.resultObj;
    for (let i = 0; i < tableData.value.length; i++) {
      tableData.value[i].afterSaleShow = false;
    }
  }
  const b = await RequestAllCause();
  if (b.msg == "操作成功！") {
    tableDataCase.value = b.resultObj;
    for (let i = 0; i < tableDataCase.value.length; i++) {
      tableDataCase.value[i].afterSaleShow = false;
    }
  }
};
const navChange = (item: any) => {
  console.log(item);
  for (let i = 0; i < list.value.length; i++) {
    const filteredClasses = list.value[i].class.filter(
      (className) => className !== "current"
    );
    list.value[i].class = filteredClasses;
  }
  item.class.push("current");
  route.value = item.route;
  //   console.log("当前route", route.value);
};
/**
 * 点击修改
 */
const deposit = ref<any>([]);
const setupEdit = (item, index) => {
  console.log("点击修改11111111111", index);
  item.afterSaleShow = !item.afterSaleShow;
  deposit.value[index] = JSON.parse(JSON.stringify(item));
  console.log("点击修改", deposit.value);
};
/**
 * 编辑确认按钮
 */
const Edit1 = (item: any) => {
  const regex = /^\d+(\.\d{1,2})?$/;
  if (!regex.test(item.value)) {
    verify.value = false;
  } else {
    verify.value = true;
  }
  if (verify.value === false) {
    ElMessage.error("请输入正确的时间");
  } else {
    new Promise((resolve, reject) => {
      RequestSettingEdit(item)
        .then((res: any) => {
          ElMessage.success("修改成功");
          item.afterSaleShow = !item.afterSaleShow;
        })
        .catch((err: any) => {
          ElMessage.error("修改失败");
        });
    });
  }
};
/**
 * 编辑取消按钮
 */
const cancle = (item: any, index: number) => {
  item.afterSaleShow = !item.afterSaleShow;
  item.value = deposit.value[index].value;
  item.timeUnit = deposit.value[index].timeUnit;
  item.enable = deposit.value[index].enable;
  item.note = deposit.value[index].note;
};
/**
 * 售后原因修改确认
 */
const Sure = (item: any) => {
  new Promise((resolve, reject) => {
    RequestAllCauseEdit(item)
      .then((res: any) => {
        ElMessage.success("修改成功");
        item.afterSaleShow = !item.afterSaleShow;
      })
      .catch((err: any) => {
        reject(err);
        ElMessage.error("修改失败");
      });
  });
};
const type = ref("Add");
/**
 * 点击添加比例
 */
const AddProportion = () => {
  mask.value = true;
  messagesShow.value = true;
  type.value = "Add";
};
/**
 * 点击修改比例
 */
const EditId = ref();
const proportionEdit = (item: any, index: number) => {
  mask.value = true;
  messagesShow.value = true;
  type.value = "Edit";
  GoodsformDate.value = {
    drawType: item.drawType,
    proportion: item.proportion,
    note: item.note,
  };
  EditId.value = item.id;
};
/**
 * 比例设置点击确认
 */

let timer = ref(null); //设置记录时间，用于防抖
const plateformSure = async () => {
  if (timer != null) {
    clearTimeout(timer);
  }
  timer = setTimeout(async () => {
    if (type.value == "Add") {
      const a = await RequestAddScaleSetting(GoodsformDate.value);
      if (a.msg == "操作成功！") {
        ElMessage.success("操作成功");
        requestsetting();
        maskBtn1();
        GoodsformDate.value = {
          drawType: "",
          proportion: "",
          note: "",
        };
      } else {
        ElMessage.error("操作失败，请重试！");
      }
    } else {
      const a = await RequestAddScaleSetting({
        id: EditId.value,
        drawType: GoodsformDate.value.drawType,
        proportion: GoodsformDate.value.proportion,
        note: GoodsformDate.value.note,
      });
      if (a.msg == "操作成功！") {
        ElMessage.success("操作成功");
        requestsetting();
        maskBtn1();
        GoodsformDate.value = {
          drawType: "",
          proportion: "",
          note: "",
        };
        EditId.value = "";
      } else {
        ElMessage.error("操作失败，请重试！");
      }
    }
  }, 500);
};
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  mask.value = false;
  messagesShow.value = false;
};
</script>

<style scoped lang="scss">
.messages {
  width: 600px;
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -300px;
  margin-top: -200px;
  z-index: 99;
  background: #fff;
}
.order_content {
  width: 98%;
  height: 90%;
  margin: 2% auto;
  background: #fff;
  .nav_ul {
    width: 100%;
    height: 50px;
    display: flex;
    border-bottom: 2px solid #f2f2f2;
    .nav_li {
      width: 70px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 14px;
      margin-left: 10px;
    }
    .first_li {
      margin-left: 40px;
    }
    .current {
      color: #1f69ff;
      border-bottom: 2px solid #1f69ff;
    }
  }
}
.add_btn {
  margin-top: 20px;
  margin-left: 30px;
}
:deep(.el-table) {
  width: 96% !important;
  border: 1px solid #ebeef5;
  margin: 20px auto;
}
</style>
